<template>
  <span :class="['z-tag', 'z-tag__' + t]">
    <slot>{{ label }}</slot>
    <span class="close" @click="closeTag" v-if="close">×</span>
  </span>
</template>

<script>
export default {
  name: "tag", // tag
  props: {
    success: [String, Number], // 多个值使用逗号分开，如1, 2, 3
    info: [String, Number],
    warning: [String, Number],
    danger: [String, Number],
    primary: [String, Number],

    absolute: {
      // 是否开启绝对相等
      type: Boolean,
      default: true
    },
    type: String,
    label: String,
    close: Boolean,

    value: [String, Number]
  },
  data() {
    return {
      attrs: ["success", "info", "warning", "danger", "primary"],
      t: "default"
    };
  },
  watch: {
    // 需要监听值得变化，否则标签颜色不会更新
    value() {
      this.t = this.generateType();
    }
  },
  mounted() {
    this.t = this.type || this.generateType();
  },
  methods: {
    /**
     * @description 根据用户指定的值，生成对应的标签状态
     * @return String
     */
    generateType() {
      let type = this.t;
      this.attrs.some(attr => {
        const attrVal = this.$props[attr];
        if (attrVal) {
          const flag = attrVal.split(",").some(item => {
            // 一个状态可以使用多个值（success -> "1, 2"）
            const _val = item.trim();
            return this.absolute ? this.value === _val : this.value == _val;
          });
          if (flag) {
            type = attr;
            return true;
          }
        }
        return false;
      });
      return type;
    },
    closeTag() {
      this.$emit("tagClose", this.label);
    }
  }
};
</script>

<style lang="scss" scoped>
.close {
  font-size: 16px;
  cursor: pointer;
}
.z-tag {
  height: 24px;
  padding: 0 5px;
  line-height: 24px;
  border-radius: 4px;
  font-size: 12px;
  text-align: center;
  display: inline-block;
  margin: 0 5px 5px 0;
  // 警告
  &.z-tag__danger {
    background: #ffecec;
    border: 1px solid rgba(255, 73, 73, 0.2);
    color: #ff4949;
  }
  // 信息
  &.z-tag__info {
    background: rgba(69, 82, 100, 0.1);
    border: rgba(69, 82, 100, 0.2);
    color: rgb(69, 82, 100);
  }
  // 成功
  &.z-tag__success {
    background: rgba(103, 194, 58, 0.1);
    border: 1px solid rgba(103, 194, 58, 0.2);
    color: rgb(103, 194, 58);
  }
  // 警告
  &.z-tag__warning {
    background: rgb(230, 162, 60);
    border: 1px solid rgba(230, 162, 60, 0.2);
    color: rgb(255, 255, 255);
  }
  // 主题色
  &.z-tag__primary {
    background: rgba(64, 158, 255, 0.1);
    border: 1px solid rgba(64, 158, 255, 0.2);
    color: rgb(64, 158, 255);
  }
  &.z-tag__default {
    color: #000;
    border: 1px solid #f2f2f2;
  }
}
</style>
